'use strict';

const _ = require('lodash');

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const { id, position } = query;
  if (id) where.id = id;
  if (position) where.position = position;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'id', 'DESC' ],
    ],
    raw: true,
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.Banner.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.create = async ctx => {
  ctx.validate({
    title: { type: 'string' },
    position: { type: 'string' },
    target: { type: 'string', required: false },
    imageHash: { type: 'string', max: 28, min: 28 },
  });
  await ctx.service.file.record('image', ctx.request.body.imageHash);
  ctx.body = await ctx.model.Banner.create(_.pick(
    ctx.request.body,
    [ 'title', 'position', 'target', 'imageHash' ]
  ));
};

exports.show = async ctx => {
  const options = { raw: true };
  const banner = await ctx.model.Banner.findByPk(ctx.params.id, options);
  if (banner) {
    ctx.body = banner;
  } else {
    ctx.status = 404;
  }
};

exports.update = async ctx => {
  const banner = await ctx.model.Banner.findByPk(ctx.params.id);
  if (banner) {
    ctx.validate({
      title: { type: 'string', required: false },
      position: { type: 'string', required: false },
      target: { type: 'string', required: false },
      imageHash: { type: 'string', max: 28, min: 28, required: false },
    });
    const { imageHash } = ctx.request.body;
    if (imageHash) ctx.service.file.record('image', imageHash);
    ctx.body = await banner.update(_.pickBy(
      _.pick(
        ctx.request.body,
        [ 'title', 'position', 'target', 'imageHash' ]
      ),
      value => value !== null
    ));
  } else {
    ctx.status = 404;
  }
};

exports.destroy = async ctx => {
  const banner = await ctx.model.Banner.findByPk(ctx.params.id);
  if (banner) {
    await banner.destroy();
    ctx.status = 204;
  } else {
    ctx.status = 404;
  }
};
